package org.androbuzz;

import java.util.ArrayList;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.text.Editable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;


public class AndroBuzzBuddiesManagerActivity extends Activity {

    public static final String TAG = "Androbuzz.BuddiesManager";

    private Button mAddAccountButton;
    private ImageButton mRemoveButton;
    private ListView mBuddiesList;
    private boolean mShowInvisible;
    private String mProfileId;
    
    final AndroBuzzDbAdapter mDb = new AndroBuzzDbAdapter(this);
    private String[] fromfields = new String[]{AndroBuzzDbAdapter.KEY_BUDDIES_NAME, AndroBuzzDbAdapter.KEY_BUDDIES_EMAIL};
    private int[] tofields = new int[] {R.id.BuddiesEntryText, R.id.BuddiesEmailText};

    public void onCreate(Bundle savedInstanceState)
    {
        Log.v(TAG, "Activity State: onCreate()");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.buddies_manager);
        Log.d(TAG, "Opening database");
        mDb.open();
        
        // Get current profile ID
    	//for (String id: mDb.findCurrentProfileId()) {
    	//		if (id.contains("0") == false) {
    	//			mProfileId = id;
    	//		}
    	//	}
        Log.d(TAG, "Getting current profile ID");
        mProfileId = mDb.findCurrentProfileId();
    	Log.d(TAG, "Set current profile Id: " + mProfileId);

        // Append UI components
    	Log.d(TAG, "Add AddButton to UI");
        mAddAccountButton = (Button) findViewById(R.id.AddBuddiesButton);
        Log.d(TAG, "Add RemoveButton to UI");
        mRemoveButton = (ImageButton) findViewById(R.id.BuddiesRemoveButton);
        Log.d(TAG, "Add ListView to UI");
        mBuddiesList = (ListView) findViewById(R.id.BuddiesList);
        
        

        // Register handler for UI elements
        Log.d(TAG, "Set OnClick to AccountButton");
        mAddAccountButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Log.d(TAG, "AddBuddiesButton clicked");
                
				LayoutInflater buddy = LayoutInflater.from(AndroBuzzBuddiesManagerActivity.this);
			    final Builder builder = new AlertDialog.Builder(AndroBuzzBuddiesManagerActivity.this);
			    
			    final View View = buddy.inflate(R.layout.buddies_edit, null); 
		        
			    final EditText nameEntry = (EditText) View.findViewById(R.id.buddiesName);
			    final EditText emailEntry = (EditText) View.findViewById(R.id.buddiesEmail);
			    
			    final Editable buddyName = nameEntry.getEditableText();
			    final Editable buddyEmail = emailEntry.getEditableText();
			        			    
			    builder.setTitle("New Buddy");
			    builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
					
					public void onClick(DialogInterface dialog, int which) {
						
						if (buddyName.length() == 0 || buddyEmail.length() == 0) {
							Log.d(TAG, "Empty name or email entry on Save action");
							Toast.makeText(AndroBuzzBuddiesManagerActivity.this, 
									"Empty entries set, no data have been saved",
									Toast.LENGTH_SHORT).show();
						}else {
							if (buddyName.length() > 0 && buddyEmail.length() > 0) {
								Log.d(TAG, "Email Value: " + buddyEmail.toString().endsWith("@gmail.com"));
								if (buddyEmail.toString().endsWith("@gmail.com") == false) {
									Toast.makeText(AndroBuzzBuddiesManagerActivity.this,
											"Invalid email, must be a Google account",
											Toast.LENGTH_SHORT).show();
									dialog.dismiss();
								}
								else {
									if (mDb.isBuddyexist(mProfileId, buddyName.toString(), buddyEmail.toString().toLowerCase()) == false) {
										Log.d(TAG, "Saving new buddy " +buddyName+ "(" +buddyEmail+ ")" + " to Database");
										mDb.addBuddy(buddyName.toString(), buddyEmail.toString().toLowerCase(), mProfileId);
									} else {
										Toast.makeText(AndroBuzzBuddiesManagerActivity.this, "Buddy already in your list", Toast.LENGTH_SHORT).show();
										dialog.dismiss();
									}
								}
							}
						}
						populateBuddiesList();
					}
				});
			    builder.setCancelable(true);
			    builder.setView(View);
			    builder.show();
            }
        });
        //initBuddiesIfEmpty();
        populateBuddiesList();
    }

    public void onDestroy() {
    	super.onDestroy();
    	mDb.close();

    }
    
    public void RemoveClickHandler(View v) {
    	long foo = mBuddiesList.getSelectedItemId();
    	
    	Log.d(TAG, "Check Item ID: " + foo);
    	Toast.makeText(AndroBuzzBuddiesManagerActivity.this, "Removed Buddy: " + foo, Toast.LENGTH_SHORT).show();
    }
    
    private void populateBuddiesList() {

        Cursor cursor = mDb.findBuddiesByName(mProfileId);
        Log.d(TAG, "Fetching buddies list on cursor: " + cursor + "cursor count " + cursor.getCount());
        startManagingCursor(cursor);

        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.buddies_entry, cursor,
                fromfields, tofields);
        adapter.areAllItemsEnabled();
        Log.d(TAG, "Start Populate list");
        mBuddiesList.setAdapter(adapter);
    }
    
    private void initBuddiesIfEmpty(){
    	Cursor cursor = mDb.findBuddiesByName(mProfileId);
    	try {
	    	if( cursor.getCount() == 0 ){
	    		for(String contact: getContactList()){
	    			Log.d(TAG,"Contact: " + contact );
	    			String name = contact;
	    			name = name.replace("@gmail.com","");
	    			mDb.addBuddy(name, contact, mProfileId);
	    		}
	    		populateBuddiesList();
	    	}
	    	else{
	    		Log.d(TAG,"initBuddiesIfEmpty: list is not empty " + cursor.getCount() );
	    	}
    	}
    	finally {
    		cursor.close();
    	}
    }
    
	private ArrayList<String> getContactList() {
		final AccountManager accountManager = AccountManager.get(getBaseContext());
		final Account[] accounts = accountManager.getAccounts();
		final int accountsCount = accounts.length;
		Log.d(TAG,"Getting the list of contacts" );
    	// The contact list
		ArrayList<String> contactList = new ArrayList<String>();
    	if( accountsCount > 0 ){
        	ContentResolver ConnectApp = this.getContentResolver();
	    	Uri contactsURI = ContactsContract.Data.CONTENT_URI;
	    	String[] projection = new String[] {ContactsContract.Data.DATA1 };
	    	String where =     ContactsContract.Data.DATA1 + " LIKE ? "; 
			
			String[] whereArgs = new String[] {"%gmail.com"}; 
	        // Get all contacts into a cursor
	        Cursor cur = ConnectApp.query(contactsURI, projection, where, whereArgs, null);
	        //this.startManagingCursor(cur);
	        try{
	        	if (cur.moveToFirst()) { 
		             do {
		                 String mail = cur.getString(cur.getColumnIndex(ContactsContract.Data.DATA1));
		                 Log.d(TAG,"MAIL => " + mail );
		                 contactList.add(mail);
		             } while (cur.moveToNext());
		        }
	        }
	       	finally{
	       		cur.close();
	       	}
    	}
    	return contactList;
     }
}
